package org.jeecg.common.util;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * TODO
 *
 * @author CSD
 * @date 2021-08-12 11:17
 */
//不知道为啥新版本的给删除了，为了不影响咱们程序，先复制过来
@Component
public class IdGeneratorSnowflake {
    private long workerId = 0;
    private long datacenterId = 1;

    private Snowflake snowflake = IdUtil.getSnowflake(workerId,datacenterId);

    @PostConstruct
    public void init(){
        try {
            workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
        }catch (Exception e){
            e.printStackTrace();
            workerId = NetUtil.getLocalhostStr().hashCode();
        }
    }
    public synchronized long snowflakeId(){
        return snowflake.nextId();

    }
    public synchronized long snowflakeId(long workerId,long datacenterId){
        Snowflake snowflake = IdUtil.getSnowflake(workerId,datacenterId);
        return snowflake.nextId();
    }

}
